package com.yb.forum.services.impl;

import com.yb.forum.common.AppResult;
import com.yb.forum.common.ResultCode;
import com.yb.forum.dao.ArticleMapper;
import com.yb.forum.exception.ApplicationException;
import com.yb.forum.model.Article;
import com.yb.forum.model.Board;
import com.yb.forum.model.User;
import com.yb.forum.services.IArticleService;
import com.yb.forum.services.IBoardService;
import com.yb.forum.services.IUserService;
import com.yb.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.tags.EditorAwareTag;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.util.Date;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Override
    public void create(Article article) {
        // 非空校验
        if(article == null || article.getUserId()==null
        || StringUtil.isEmpty(article.getTitle())
        || StringUtil.isEmpty(article.getContent())
        || article.getBoardId() ==null){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 向数据库中写数据,设置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setDeleteState((byte)0);
        article.setState((byte)0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);


        int row = articleMapper.insertSelective(article);
        if(row <=0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 更新用户的发帖数
        User user = userService.selectById(article.getUserId());
        if(user ==null){
            log.warn(ResultCode.FAILED_CREATE.toString()+" 更新用户贴子数失败: userId = " + article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 更新用户的发帖数
        userService.addOneArticleCountById(user.getId());


        // 获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        if(board == null){
            log.warn(ResultCode.FAILED_CREATE.toString()+ " 更新板块帖子数失败: boardId = " + article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 更新板块的发帖数
        boardService.addOneArticleCountById(board.getId());

        log.info(ResultCode.SUCCESS.toString()+" userId = "+user.getId()+
                ", board Id = "+article.getId()+
                ", articleId = "+article.getId()+"  发帖成功!!!");

    }
}
